import {
  Box,
  Button,
  Divider,
  Flex,
  Heading,
  HStack,
  IconButton,
  Input,
  Stack,
  Text,
  useToast,
} from '@chakra-ui/react';
import { DeleteIcon } from '@chakra-ui/icons';
import { useMemo } from 'react';
import { useCart } from '../hooks/useCart';

const CartPage = () => {
  const { items, total, loading, error, updateQuantity, removeItem, clear } = useCart();
  const toast = useToast();

  const hasItems = items.length > 0;

  const handleQuantityChange = async (productId: string, value: string) => {
    const numeric = Number(value);
    if (Number.isNaN(numeric)) {
      return;
    }
    await updateQuantity(productId, numeric);
  };

  const formattedTotal = useMemo(() => total.toFixed(2), [total]);

  return (
    <Stack spacing={4}>
      <Box bg="white" borderRadius="2xl" border="1px solid" borderColor="gray.200" p={6}>
        <Flex
          justify="space-between"
          align={{ base: 'flex-start', md: 'center' }}
          direction={{ base: 'column', md: 'row' }}
          gap={3}
        >
          <Heading size="md">Shopping Cart</Heading>
          {hasItems && (
            <Button
              colorScheme="red"
              variant="outline"
              size="sm"
              onClick={() => {
                void clear();
                toast({
                  title: 'Cart cleared',
                  status: 'info',
                  duration: 2500,
                  isClosable: true,
                });
              }}
            >
              Clear Cart
            </Button>
          )}
        </Flex>
        {loading ? (
          <Text color="gray.500" mt={4}>
            Loading items...
          </Text>
        ) : hasItems ? (
          <Stack spacing={4} mt={4}>
            {items.map((item) => (
              <Box
                key={item.productId}
                border="1px solid"
                borderColor="gray.100"
                rounded="xl"
                p={4}
              >
                <Flex
                  justify="space-between"
                  align={{ base: 'flex-start', md: 'center' }}
                  direction={{ base: 'column', md: 'row' }}
                  gap={4}
                >
                  <Box>
                    <Text fontWeight="600">{item.productName}</Text>
                    <Text color="gray.500" fontSize="sm">
                      Unit price: ${item.unitPrice.toFixed(2)}
                    </Text>
                  </Box>
                  <HStack spacing={3}>
                    <Input
                      type="number"
                      min="1"
                      width="80px"
                      value={item.quantity}
                      onChange={(e) => handleQuantityChange(item.productId, e.target.value)}
                    />
                    <Text fontWeight="600">
                      ${(item.unitPrice * item.quantity).toFixed(2)}
                    </Text>
                    <IconButton
                      aria-label="Remove"
                      icon={<DeleteIcon />}
                      variant="ghost"
                      colorScheme="red"
                      onClick={() => void removeItem(item.productId)}
                    />
                  </HStack>
                </Flex>
              </Box>
            ))}
          </Stack>
        ) : (
          <Text color="gray.500" mt={4}>
            Your cart is empty. Browse products to add items.
          </Text>
        )}
        {error && (
          <Text color="orange.500" fontSize="sm" mt={4}>
            {error}
          </Text>
        )}
      </Box>

      <Box bg="white" borderRadius="2xl" border="1px solid" borderColor="gray.200" p={6}>
        <Heading size="md" mb={4}>
          Summary
        </Heading>
        <Stack spacing={3}>
          <Flex justify="space-between">
            <Text color="gray.600">Subtotal</Text>
            <Text fontWeight="600">${formattedTotal}</Text>
          </Flex>
          <Flex justify="space-between">
            <Text color="gray.600">Shipping</Text>
            <Text color="gray.500">Calculated at checkout</Text>
          </Flex>
          <Divider />
          <Flex justify="space-between">
            <Text fontSize="lg" fontWeight="600">
              Total
            </Text>
            <Text fontSize="lg" fontWeight="700">
              ${formattedTotal}
            </Text>
          </Flex>
          <Button colorScheme="brand" isDisabled={!hasItems}>
            Proceed to Checkout
          </Button>
        </Stack>
      </Box>
    </Stack>
  );
};

export default CartPage;
